﻿

namespace Catalog.API.Products.CreateProduct
{
    //由前端发送的请求对象内部序列化成CreateProductRequest record,作为参数传入到CreateProductEndpoint中
    //CreateProductEndpoint将请求对象转换为命令对象CreateProductCommand,并将命令对象发送到Mediator中,Mediator将命令对象转换为命令执行结果CreateProductResult,并将结果转换为响应对象CreateProductResponse,并返回httpResponse
    public record CreateProductRequest(string Name, string Description, decimal Price, string ImageFile, List<string> Categories);
    public record CreateProductResponse(Guid Id);

   
    public class CreateProductEndpoint : ICarterModule
    {
        public void AddRoutes(IEndpointRouteBuilder app)
        {
            //将客户端post请求路由到委托中
            app.MapPost("/products", async (CreateProductRequest request, ISender sender) =>
            {
                //将客户端请求转换为命令对象
                var command = request.Adapt<CreateProductCommand>();
                //发送命令对象到Mediator中,返回命令执行结果：CreateProductResult
                var result = await sender.Send(command);
                //将命令执行结果转换为响应对象
                var response = result.Adapt<CreateProductResponse>();
                //返回 httpResponse
                return Results.Created($"/products/{response.Id}", response);
            })
           .WithName("CreateProduct")
           .Produces<CreateProductResponse>(StatusCodes.Status201Created)
           .ProducesProblem(StatusCodes.Status400BadRequest)
           .WithSummary("Create  product")
           .WithDescription("Create a new product with the given name, description, price, image url and category");

        }
    }
}
